#!/bin/bash

# config
#PUBLISHER_HOST="localhost"
#PUBLISHER_PORT="20034"
PUBLISHER_ADDR="http://${PUBLISHER_HOST}:${PUBLISHER_PORT}/sign-files"
POST_KEY_BASE64="encoded_file_content"
POST_KEY_MD5="file_md5"
REQ_KEY_BASE64="signed_file_content"
REQ_KEY_MD5="signed_file_md5"

# function definition
get_json_value(){
	echo "$1" | awk -F "[{,:}]" '{for(i=1;i<NF;i++){if($i~"'$2'"){print $(i+1)}}}' | sed 's/\"//g'
}

file="$1"
file_base64="$(base64 $file)"
file_md5="$(md5sum $file | awk '{printf $1}')"
json="{\"$POST_KEY_BASE64\":\"$file_base64\", \"$POST_KEY_MD5\":\"$file_md5\"}"

req="$(curl -X POST "$PUBLISHER_ADDR" -H 'Content-Type: application/json' -d "$json")"
[ $? -eq 0 ] || { echo "Fail to post sign service, REQ="; echo "req"; exit 1; }

sig_base64=$(get_json_value "$req" "$REQ_KEY_BASE64")
[ $? -eq 0 ] || { echo "Fail to parser $REQ_KEY_BASE64"; exit 1; }
echo -e "$sig_base64" | base64 -d > $file.sig
[ $? -eq 0 ] || { echo "Fail to decode value of $key"; exit 1; }

sig_md5=$(get_json_value "$req" "$REQ_KEY_MD5")
[ $? -eq 0 ] || { echo "Fail to parser $REQ_KEY_MD5"; exit 1; }
md5sum $file.sig | grep "$sig_md5"
[ $? -eq 0 ] || { echo "Fail to check md5 of $file.sig"; exit 1; }

echo "Sign $file ok!"
exit 0
